<?php
/**
 ***********************************************************************************************************************
 * 默认采用加密方式的cookie  AES加密方式
 ***********************************************************************************************************************
 */
namespace artisan;
/**
 * Class cookie
 */
class cookie
{
    /**
     * @param string $name
     * @param string $value
     * @param string $expire
     * @param string $domain
     * @param string $path
     */
    public static function set($name = '', $value = '', $expire = '', $domain = '', $path = '/')
    {
        if (is_array($name))
        {
            foreach (array('value', 'expire', 'domain', 'path', 'name') as $item)
            {
                if (isset($name[$item]))
                {
                    $$item = $name[$item];
                }
            }
        }

        if ($domain == '') {
            $domain = input::getHost();
        }

        // 有效时间设置
        $_expires = globalConfig('cookie.expires');

        if (!is_numeric($expire)) {
            $expire = is_numeric($_expires) ? time() + $_expires : time() + 86400;
        } else {
            $expire = time() + $expire;
        }

        if(!empty($value)) {
            $value = serialize($value);
        }
        // 是否开启加密
        $_key = globalConfig('cookie.key');
        if(!empty($value) && !empty($_key)) {
            $value = aes::encrypt($value, $_key);
        }

        return setcookie($name, $value, $expire, $path, $domain);
    }

    /**
     * @param $name
     */
    public static function remove($name)
    {
        return self::set($name, null, (time() - 2592000));
    }

    /**
     * @param $name
     * @return string
     */
    public static function get($name = '')
    {
        if(empty($name) || !isset($_COOKIE[$name]) || empty($_COOKIE[$name])) {
            return '';
        }

        // 是否开启加密
        $_key = globalConfig('cookie.key');
        if(empty($_key)) {
            return unserialize($_COOKIE[$name]);
        }

        $value = aes::decrypt($_COOKIE[$name], $_key);

        if(empty($value)) {
            return '';
        }
        return @unserialize($value);
    }

}